package com.atguigu.chapter07.state;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/15 14:02
 */
public class Flink03_State_Key_Value {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
            .getExecutionEnvironment()
            .setParallelism(3);
        env
            .socketTextStream("hadoop162", 9999)
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private ValueState<Integer> vcState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 监控状态托管给了运行时对象
                    vcState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVcState", Integer.class));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    // 连续两次水位的差值超过10, 就预警
                    
                    Integer lastVc = vcState.value(); // 从单值的状态中获取值
                    
                    if (lastVc != null && Math.abs(value.getVc() - lastVc) > 10) {
                        out.collect(ctx.getCurrentKey() + " 水位变动比较大, 发出预警");
                    }
                    vcState.update(value.getVc()); // 更新状态的值
                }
            })
            .print();
        
        env.execute();
        
    }
}
